<template>
  <div>
    <el-form-item :label="LabelText">
      <el-input
        v-model="input"
        :placeholder="props.Placeholder != '' ? props.Placeholder : '按回车(Enter)保存输入项到本地'"
        :rows="props.Rows"
        :type="inputType"
        @keydown.enter="saveInput"
      >
        <template #append>
          <el-button @click="showOrHidePanel"><span style="font-size: 18px">📋</span></el-button>
        </template>
      </el-input>
      <el-card v-show="historyPanelVisible" :class="''" class="box-card" style="margin-top: 0px">
        <el-row>
          <div v-for="(item, i) in historyList" :key="item" style="margin: 2px 3px; cursor: pointer" @click="fillInput(item)">
            <el-tag :type="colors[i % 4]" closable @close="DelTag(item)">{{ item }}</el-tag>
          </div>
          <div v-if="!historyList || historyList.length <= 0">
            <el-empty :image-size="30" description="无输入记录，输入后按回车即可保存" style="height: 12px" />
          </div>
        </el-row>
      </el-card>
    </el-form-item>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from "vue";
import { fa } from "element-plus/es/locale";
import { ElMessage } from "element-plus";

const props = defineProps({
  FieldName: {
    type: String,
    required: true,
    default: "field"
  },
  LabelText: {
    type: String,
    required: true,
    default: "请输入"
  },
  SelectMany: {
    type: Boolean,
    required: true,
    default: false
  },
  fillHistoryFirst: {
    //自动填充历史第一个和
    type: Boolean,
    required: false,
    default: true
  },
  DefaultValue: {
    //默认值
    type: String,
    required: false,
    default: ""
  },
  Placeholder: {
    //提示词
    type: String,
    required: false,
    default: ""
  },
  Rows: {
    //行数，默认1 大于1时为textarea
    type: Number,
    required: false,
    default: 1
  }
});
let inputType = ref("text");
// let inputRows = ref(1);
onMounted(() => {
  if (props.Rows > 1) {
    inputType.value = "textarea";
    // inputRows.value = props.Rows;
  }
  getHistoryList();
  if (props.fillHistoryFirst && historyList.value.length > 0) {
    input.value = historyList.value[0];
  }
  if (props.DefaultValue != "") {
    input.value = props.DefaultValue;
  }
});

watch(
  () => props.DefaultValue,
  (newVal: string, oldVal: string) => {
    input.value = newVal;
  }
);

const input = ref("");
const historyList = ref([]);
const historyPanelVisible = ref(false);
const colors = ref(["success", "info", "danger", "warning"]);

const getHistoryList = () => {
  const history = localStorage.getItem(`field_${props.FieldName}_history`);
  if (history) {
    historyList.value = JSON.parse(history);
  }
};

const saveInput = () => {
  if (input.value && input.value != "") {
    if (historyList.value.includes(input.value)) {
      //Success("输入项" + input.value + "已存在，不重复保存")
    } else {
      historyList.value.unshift(input.value);
      if (historyList.value.length > 10) {
        historyList.value.pop();
      }
      localStorage.setItem(`field_${props.FieldName}_history`, JSON.stringify(historyList.value));
      Success("输入项" + input.value + "已经保存到本地");
    }
  } else {
    Success("输入项为空");
  }
  historyPanelVisible.value = false;
  CallBackLocal(input.value);
};

const CallBackLocal = (value: string) => {
  //通知父组件
  emits("Callback", props.FieldName, value);
};

const Success = (content: string) => {
  ElMessage({ type: "success", message: content });
};
const Error = (content: string) => {
  ElMessage({ type: "success", message: content });
};
const fillInput = value => {
  if (props.SelectMany && input.value) {
    if (!input.value.split(",").includes(value)) {
      input.value = input.value == "" ? value : input.value + "," + value;
    }
  } else {
    input.value = value;
  }
  if (!props.SelectMany) {
    historyPanelVisible.value = false;
  }
  let index = historyList.value.indexOf(value);
  if (index > -1) {
    let temp = historyList.value[0];
    historyList.value[0] = value;
    historyList.value[index] = temp;
    localStorage.setItem(`field_${props.FieldName}_history`, JSON.stringify(historyList.value));
  }
};

const DelTag = TagName => {
  let newList = [];
  for (let index = 0; index < historyList.value.length; index++) {
    const item = historyList.value[index];
    if (item == TagName) {
      continue;
    }
    newList.push(item);
  }
  historyList.value = newList;
  localStorage.setItem(`field_${props.FieldName}_history`, JSON.stringify(historyList.value));
};

const showOrHidePanel = () => {
  historyPanelVisible.value = !historyPanelVisible.value;
};

const handleBlur = () => {
  console.log("组件失去焦点");
  // if (input.value != "") {
  //   historyPanelVisible.value = false
  // }
  // if (input.value == "" && historyList.value.length == 0) {
  //   historyPanelVisible.value = false
  // }
};

const SetInputValue = (val: any) => {
  if (!val || val == "") {
    val = historyList.value[0];
  }
  input.value = val;

  CallBackLocal(input.value);
};

const ShowHistoryPanel = () => {
  getHistoryList();
  historyPanelVisible.value = true;
};

const CheckWrite = () => {
  if (input.value && input.value != "") {
    return true;
  }
  Error("【" + props.LabelText + "】未填写");
  return false;
};

const emits = defineEmits(["Callback"]);
watch(input, (nval, oval) => {
  emits("Callback", props.FieldName, nval);
});
</script>
